import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import {
  Button,
  Col,
  Drawer,
  Form,
  FormProps,
  Input,
  InputNumber,
  Radio,
  Row,
  Select,
  Space,
  Tag
} from 'antd';

import { store } from '@/store';

import {
  proIndicatorDataAdd,
  proIndicatorDataUpdate
} from '@/services/bizApi/shengchanzhibiaoshujujiekou';
import { proIndicatorInfoReportTimeList } from '@/services/bizApi/shengchanzhibiaoxinxijiekou';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

type BizObject = BIZAPI.ProIndicatorDataEntity;

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
          infoId: string;
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          infoId: string;
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          infoId: string;
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [reportTimeOptions, setReportTimeOptions] = useState<string[]>([]);

  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values
      };
      if (args?.type === 'edit') {
        query.id = args?.rowData?.id;
        query.infoId = args?.rowData?.infoId;
        await proIndicatorDataUpdate(query);
      } else {
        query.infoId = args?.infoId;
        await proIndicatorDataAdd(query);
      }

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'add' ? '新增指标数据成功' : '编辑指标数据成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(async () => {
          //获取填报时间下拉列表
          const res = await proIndicatorInfoReportTimeList({
            id: arg?.infoId as string
          });

          setReportTimeOptions(res.data as string[]);

          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData
            });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');
      return;
    }
    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增指标数据',
          edit: '编辑指标数据',
          detail: '指标数据详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 10 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Row>
          <Col span={12}>
            <Form.Item
              label="填报时间"
              name="reportTime"
              rules={[
                {
                  required: true,
                  message: '请选择报告时间'
                }
              ]}
            >
              <Select
                style={{ width: '100%' }}
                placeholder="请选择报告时间"
                options={reportTimeOptions?.map((item: string) => ({
                  value: item,
                  label: item
                }))}
              />
            </Form.Item>
          </Col>
        </Row>
        <h3>工艺消耗</h3>
        <Row>
          <Col span={12}>
            <Form.Item
              name="yfldsxh"
              rules={[
                {
                  required: true,
                  message: '请输入原辅料吨水消耗'
                }
              ]}
              label="原辅料吨水消耗"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入原辅料吨水消耗"
                suffix="元/T"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="dndsxh"
              rules={[
                {
                  required: true,
                  message: '请输入电能吨水消耗'
                }
              ]}
              label="电能吨水消耗"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入电能吨水消耗"
                suffix="元/T"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="zlsdsxh"
              rules={[
                {
                  required: true,
                  message: '请输入自来水吨水消耗'
                }
              ]}
              label="自来水吨水消耗"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入自来水吨水消耗"
                suffix="元/T"
              />
            </Form.Item>
          </Col>
        </Row>

        <h3>工艺控制</h3>
        <h4 style={{ paddingLeft: '25px' }}>
          <Tag color="blue">一、二级DO控制</Tag>
        </h4>
        <Row>
          <Col span={12}>
            <Form.Item
              name="shaxyjory"
              rules={[
                {
                  required: true,
                  message: '请输入生化A线一级O溶氧'
                }
              ]}
              label="生化A线一级O溶氧"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入生化A线一级O溶氧"
                suffix="mg/l"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="shaxejory"
              rules={[
                {
                  required: true,
                  message: '请输入生化A线二级O溶氧'
                }
              ]}
              label="生化A线二级O溶氧"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入生化A线二级O溶氧"
                suffix="mg/l"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="shbxyjory"
              rules={[
                {
                  required: true,
                  message: '请输入生化B线一级O溶氧'
                }
              ]}
              label="生化B线一级O溶氧"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入生化B线一级O溶氧"
                suffix="mg/l"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="shbxejory"
              rules={[
                {
                  required: true,
                  message: '请输入生化B线二级O溶氧'
                }
              ]}
              label="生化B线二级O溶氧"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入生化B线二级O溶氧"
                suffix="mg/l"
              />
            </Form.Item>
          </Col>
        </Row>

        <h4 style={{ paddingLeft: '25px' }}>
          <Tag color="blue">MBR膜池运行稳定性</Tag>
        </h4>
        <Row>
          <Col span={12}>
            <Form.Item
              name="mbrmsftzcs"
              rules={[
                {
                  required: true,
                  message: '请选择MBR膜是否停止产水'
                }
              ]}
              label="MBR膜是否停止产水"
            >
              <Radio.Group>
                <Radio value={true}>是</Radio>
                <Radio value={false}>否</Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
          {/** MBR膜是否停止产水为否时，填写MBR膜池运行稳定性 */}
          <Col span={24}>
            <Form.Item noStyle dependencies={['mbrmsftzcs']}>
              {({ getFieldValue }) => {
                return getFieldValue('mbrmsftzcs') ? (
                  <>
                    <Row>
                      <Col span={12}>
                        <Form.Item
                          name="mbrmtzcsyy"
                          rules={[
                            {
                              required: true,
                              message: '请选择停产原因'
                            }
                          ]}
                          label="停止产水原因"
                        >
                          <Select
                            style={{ width: '100%' }}
                            placeholder="请选择停止产水原因"
                            options={[
                              {
                                label: '无合理理由',
                                value: '无合理理由'
                              },
                              {
                                label: '设备损坏',
                                value: '设备损坏'
                              },
                              {
                                label: '设施损坏',
                                value: '设施损坏'
                              }
                            ]}
                          />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item name="mbrmtzcsyyms" label="停止产水原因描述">
                          <Input.TextArea
                            style={{ width: '100%' }}
                            placeholder="请输入停止产水原因描述"
                            autoSize={{ minRows: 4, maxRows: 6 }}
                          />
                        </Form.Item>
                      </Col>
                    </Row>
                  </>
                ) : null;
              }}
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="mbrmcywa1"
              rules={[
                {
                  required: true,
                  message: '请输入MBR膜池液位A1'
                }
              ]}
              label="MBR膜池液位A1"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入MBR膜池液位A1"
                suffix="米"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="mbrmcywa2"
              rules={[
                {
                  required: true,
                  message: '请输入MBR膜池液位A2'
                }
              ]}
              label="MBR膜池液位A2"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入MBR膜池液位A2"
                suffix="米"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="mbrmcywb1"
              rules={[
                {
                  required: true,
                  message: '请输入MBR膜池液位B1'
                }
              ]}
              label="MBR膜池液位B1"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入MBR膜池液位B1"
                suffix="米"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="mbrmcywb2"
              rules={[
                {
                  required: true,
                  message: '请输入MBR膜池液位B2'
                }
              ]}
              label="MBR膜池液位B2"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入MBR膜池液位B2"
                suffix="米"
              />
            </Form.Item>
          </Col>
        </Row>
        <h4 style={{ paddingLeft: '25px' }}>
          <Tag color="blue">Fendon产水COD控制效果</Tag>
        </h4>
        <Row>
          <Col span={12}>
            <Form.Item
              name="fdcscod"
              rules={[
                {
                  required: true,
                  message: '请输入芬顿出水cod'
                }
              ]}
              label="芬顿出水cod"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入芬顿出水cod"
                suffix="mg/l"
              />
            </Form.Item>
          </Col>
        </Row>
        <h4 style={{ paddingLeft: '25px' }}>
          <Tag color="blue">气浮刮泥控水指标</Tag>
        </h4>
        <Row>
          <Col span={12}>
            <Form.Item
              name="qfjsss"
              rules={[
                {
                  required: true,
                  message: '请输入气浮进水ss'
                }
              ]}
              label="气浮进水ss"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入气浮进水ss"
                suffix="mg/l"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="qfcsss"
              rules={[
                {
                  required: true,
                  message: '请输入气浮出水ss'
                }
              ]}
              label="气浮出水ss"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入气浮出水ss"
                suffix="mg/l"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="qfjsl"
              rules={[
                {
                  required: true,
                  message: '请输入气浮进水量'
                }
              ]}
              label="气浮进水量"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入气浮进水量"
                suffix="mg/l"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="qfgzhsl"
              rules={[
                {
                  required: true,
                  message: '请输入气浮刮渣含水率'
                }
              ]}
              label="气浮刮渣含水率"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入气浮刮渣含水率"
                suffix="%"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="wncybhz"
              rules={[
                {
                  required: true,
                  message: '请输入污泥池液变化值'
                }
              ]}
              label="污泥池液变化值"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入污泥池液变化值"
                suffix="t"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="lxjjll"
              rules={[
                {
                  required: true,
                  message: '请输入离心机进料量'
                }
              ]}
              label="离心机进料量"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入离心机进料量"
                suffix="t"
              />
            </Form.Item>
          </Col>
        </Row>

        <h4 style={{ paddingLeft: '25px' }}>
          <Tag color="blue">处理水量效率</Tag>
        </h4>
        <Row>
          <Col span={12}>
            <Form.Item
              name="shsjclz"
              rules={[
                {
                  required: true,
                  message: '请输入生化实际处理值'
                }
              ]}
              label="生化实际处理值"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入生化实际处理值"
                suffix="t"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="gyzdshclz"
              rules={[
                {
                  required: true,
                  message: '请输入工艺指定生化处理值'
                }
              ]}
              label="工艺指定生化处理值"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入工艺指定生化处理值"
                suffix="t"
              />
            </Form.Item>
          </Col>
        </Row>

        <h4 style={{ paddingLeft: '25px' }}>
          <Tag color="blue">在线检测排放指标</Tag>
        </h4>
        <Row>
          <Col span={12}>
            <Form.Item
              name="bafcscod"
              rules={[
                {
                  required: true,
                  message: '请输入BAF出水cod'
                }
              ]}
              tooltip="大于68.26超标，请输入超标原因"
              label="BAF出水cod"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入BAF出水cod"
                suffix="mg/l"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="bafcsad"
              dependencies={['bafcsad']}
              rules={[
                {
                  required: true,
                  message: '请输入BAF出水氨氮'
                }
              ]}
              tooltip="大于10.24超标，请输入超标原因"
              label="BAF出水氨氮"
            >
              <InputNumber
                min={0.1}
                style={{ width: '100%' }}
                placeholder="请输入BAF出水氨氮"
                suffix="mg/l"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item dependencies={['bafcscod', 'bafcsad']} noStyle>
              {({ getFieldValue }) => {
                return getFieldValue('bafcscod') > 68.26 || getFieldValue('bafcsad') > 10.24 ? (
                  <Form.Item
                    name="bafcscodadcbyy"
                    rules={[
                      {
                        required: true,
                        message: '请输入超标原因'
                      }
                    ]}
                    label="超标原因"
                  >
                    <Input.TextArea
                      style={{ width: '100%' }}
                      placeholder="请输入超标原因"
                      autoSize={{ minRows: 4, maxRows: 6 }}
                    />
                  </Form.Item>
                ) : null;
              }}
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
